/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.wii.elpro.web.action;

import com.wii.elpro.dao.ProdukDAOInterface;
import com.wii.elpro.dao.hb.ProdukDAOImpl;
import com.wii.elpro.entity.Produk;
import com.wii.elpro.entity.User;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 *
 * @author hp02
 */
public class ProductDeleteMaterialAction extends Action {
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession sess = request.getSession(true);
        User user = (User)sess.getAttribute("userSession");       
        if(user==null){
            return mapping.findForward("gagalLogin");            
        }  
        ActionForward af = null;
        int index = Integer.parseInt(request.getParameter("id"));
        ProdukDAOInterface dao = new ProdukDAOImpl();       
        ActionMessages messages = new ActionMessages();
        long idProduct=0;
        if(sess.getAttribute("idProduct")!=null) {
            idProduct = Long.parseLong((String) sess.getAttribute("idProduct"));
        }
        try {
            Produk p = dao.getProduk(idProduct);
            p.getProdukMaterials().remove(index);
            dao.update(p);
            messages.add("customMessage", new ActionMessage("customMessage", "Your data is successfully deleted."));
            saveMessages(sess, messages);
            af = new ActionForward(mapping.findForward("success").getPath()+"?id="+idProduct, true);
        } catch (Exception ex) {
            ex.printStackTrace();    
            messages.add("message", new ActionMessage("customMessage", "Application is fail to delete your data. Please contact my developer."));
            saveMessages(sess, messages);
            af = new ActionForward(mapping.findForward("success").getPath()+"?id="+idProduct, true);
        }
        return af;
    }
}
